#include "mainwindow.h"
#include "ui_mainwindow.h"

#include  <qdebug>
#include  <QFile>
#include  <QDateTime>
#include "comfunc.h"

extern int g_argc;
extern char *g_argv[10];

enum FlashType
{
    GD32Flash = 0,
    En25916Flash,
};

struct BlkInfor
{
    uint32_t startAddrInFile;
    uint16_t size;
    uint32_t dstAddrInFlash;
    uint16_t crc;
    uint8_t  flashType;
};



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->textEditArg->append(QString::asprintf("参数的数目=%d \n", g_argc));
    for(int i=0; i<g_argc;i++)
    {
        ui->textEditArg->insertPlainText( QString::asprintf("[%d]: ", i) + g_argv[i] + "\n");
    }

}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_pushButtonPackage_clicked()
{
    struct BlkInfor blk_infor_app_bin;

    QString path_app_bin = "未拖入任何文件";//应用层的bin文件路径

    if( ui->textEditPathAppBin->toPlainText().isEmpty() )
    {

    }
    else
    {
        path_app_bin = ui->textEditPathAppBin->toPlainText();//file:///E:/test/a.bin
        path_app_bin.remove(0,8);//删掉前面的file:///
    }

    QFile file(path_app_bin);
    if (!file.open(QIODevice::ReadOnly))//追加模式QIODevice::Append
    {
        ui->textEditShow->append("读文件->打开失败，文件路径:" + path_app_bin );
        return;
    }
    else
    {
        ui->textEditShow->append("读文件->打开成功");
    }

    char file_bin[0x2000];
    QDataStream in(&file);
    uint realLen=0;
    realLen = in.readRawData(file_bin, sizeof(file_bin));
    ui->textEditShow->append(QString("文件大小 = %1 字节").arg(realLen));
    blk_infor_app_bin.size = realLen;

    uint16_t crc_ret = sp_crc16_with_init(0, (const uint8_t *)file_bin, realLen);
    blk_infor_app_bin.crc = crc_ret;

    ui->textEditShow->append(QString("CRC = 0x%1 ").arg(crc_ret,4,16,QChar('0')));

    file.close();

}
//void MainWindow::on_pushButtonPackage_clicked()
//{
//    QFile file("E:\\test\\a.bin");

//    if (!file.open(QIODevice :: WriteOnly | QIODevice :: Truncate))
//    {
//        qDebug()<<"写文件->打开失败";
//        return;
//    }
//    else
//    {
//        qDebug()<<"写文件->打开成功";
//    }

//    QDataStream out(&file);
//    //out << QString("Qt");		//---写入：Qt
//    uint8_t var = 0x5A;
//    out << var;
//    file.close();


//    if (!file.open(QIODevice::ReadOnly))
//    {
//        qDebug()<<"读文件->打开失败";
//        return;
//    }
//    else
//    {
//        qDebug()<<"读文件->打开成功";
//    }

//    QDataStream in(&file);
//    uint8_t readVar=0;
//    in >> readVar;
//    file.close();

//    ui->textEditShow->setText( QString::number(readVar,16) );
//}

void MainWindow::on_pushButtonClear_clicked()
{
    ui->textEditShow->setText("");
}
